<template>
  <div class="min-h-screen bg-gradient-to-br from-primary-50 to-blue-100 flex items-center justify-center p-4">
    <div class="card w-full max-w-sm">
      <div class="text-center mb-8">
        <h1 class="text-2xl font-bold text-gray-900 mb-2">SmartInput</h1>
        <p class="text-gray-600">智能语音输入系统</p>
      </div>

      <!-- 网络状态检测 -->
      <div v-if="networkError" class="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
        <div class="text-red-600 text-sm">
          <div class="font-medium">网络连接问题</div>
          <div class="text-xs mt-1">{{ networkError }}</div>
        </div>
      </div>

      <form @submit.prevent="handleSubmit" class="space-y-6">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">
            用户名
          </label>
          <input
            v-model="formData.username"
            type="text"
            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
            placeholder="请输入用户名"
            required
            :disabled="loading"
          />
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">
            密码
          </label>
          <input
            v-model="formData.password"
            type="password"
            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
            placeholder="请输入密码"
            required
            :disabled="loading"
            minlength="6"
          />
        </div>

        <div v-if="!isLogin">
          <label class="block text-sm font-medium text-gray-700 mb-2">
            确认密码
          </label>
          <input
            v-model="formData.confirmPassword"
            type="password"
            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
            placeholder="请再次输入密码"
            required
            :disabled="loading"
            minlength="6"
          />
        </div>

        <div v-if="error" class="text-red-600 text-sm text-center bg-red-50 p-3 rounded-lg">
          {{ error }}
        </div>

        <button
          type="submit"
          :disabled="loading"
          class="btn-primary w-full disabled:opacity-50"
        >
          {{ loading ? '处理中...' : (isLogin ? '登录' : '注册') }}
        </button>
      </form>

      <div class="mt-6 text-center">
        <button
          @click="toggleMode"
          class="text-primary-600 hover:text-primary-700 text-sm"
          :disabled="loading"
        >
          {{ isLogin ? '没有账号？立即注册' : '已有账号？立即登录' }}
        </button>
      </div>

      <div v-if="!isLogin" class="mt-4 text-xs text-gray-500 text-center">
        注册即表示同意我们的服务条款和隐私政策
      </div>

      <!-- 调试信息 -->
      <div v-if="showDebug" class="mt-4 p-3 bg-gray-50 rounded-lg text-xs text-gray-600">
        <div>API地址: {{ apiUrl }}</div>
        <div>网络状态: {{ networkStatus }}</div>
        <div>用户代理: {{ userAgent }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useAppStore } from '@/store';
import { authAPI, deviceAPI } from '@/services/api';
import { communicationService } from '@/services/communication';
import { config } from '@/utils/config';

const store = useAppStore();

const isLogin = ref(true);
const loading = ref(false);
const error = ref('');
const networkError = ref('');
const showDebug = ref(false);

const formData = reactive({
  username: '',
  password: '',
  confirmPassword: ''
});

// 调试信息
const apiUrl = ref('');
const networkStatus = ref('');
const userAgent = ref('');

onMounted(async () => {
  // 检测网络状态
  await checkNetworkStatus();
  
  // 在开发环境显示调试信息
  if (import.meta.env.DEV) {
    showDebug.value = true;
    apiUrl.value = config.api.baseUrl;
    userAgent.value = navigator.userAgent;
  }
});

const checkNetworkStatus = async () => {
  try {
    // 测试网络连接
    const response = await fetch(`${config.api.baseUrl}/api/auth/test`, {
      method: 'GET',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    if (response.ok) {
      networkStatus.value = '连接正常';
      networkError.value = '';
    } else {
      networkStatus.value = `服务器响应错误: ${response.status}`;
      networkError.value = `服务器返回错误状态码: ${response.status}`;
    }
  } catch (err: any) {
    console.error('网络检测失败:', err);
    networkStatus.value = '连接失败';
    
    if (err.message.includes('Failed to fetch') || err.message.includes('NetworkError')) {
      networkError.value = '无法连接到服务器，请检查：\n1. 后端服务是否正在运行\n2. 网络连接是否正常\n3. 防火墙设置';
    } else if (err.message.includes('CORS')) {
      networkError.value = '跨域请求被阻止，请检查后端CORS配置';
    } else {
      networkError.value = `网络错误: ${err.message}`;
    }
  }
};

const handleSubmit = async () => {
  loading.value = true;
  error.value = '';

  // 注册时的密码确认验证
  if (!isLogin.value && formData.password !== formData.confirmPassword) {
    error.value = '两次输入的密码不一致';
    loading.value = false;
    return;
  }

  // 密码长度验证
  if (formData.password.length < 6) {
    error.value = '密码长度至少6位';
    loading.value = false;
    return;
  }

  try {
    if (isLogin.value) {
      // 登录
      console.log('尝试登录:', { username: formData.username });
      const response = await authAPI.login(formData.username, formData.password);
      console.log('登录响应:', response);
      
      if (response.success && response.data) {
        const userData = response.data;
        store.setUser({ 
          id: userData.userId, 
          username: userData.userName, 
          phone: '' 
        });
        store.setToken(userData.token);
        console.log('登录成功，用户信息已保存');
        
        // 自动生成设备ID并连接WebSocket
        await setupDeviceAfterLogin();
      } else {
        throw new Error(response.status?.message || '登录失败');
      }
    } else {
      // 注册
      console.log('尝试注册:', { username: formData.username });
      const response = await authAPI.register(formData.username, formData.password);
      console.log('注册响应:', response);
      
      if (response.success && response.data) {
        const userData = response.data;
        store.setUser({ 
          id: userData.userId, 
          username: userData.userName, 
          phone: '' 
        });
        store.setToken(userData.token);
        console.log('注册成功，用户信息已保存');
        
        // 自动生成设备ID并连接WebSocket
        await setupDeviceAfterLogin();
      } else {
        throw new Error(response.status?.message || '注册失败');
      }
    }
  } catch (err: any) {
    console.error('认证错误:', err);
    
    // 详细的错误处理
    if (err.response) {
      // 服务器响应了错误状态码
      const status = err.response.status;
      const data = err.response.data;
      
      if (status === 401) {
        error.value = '用户名或密码错误';
      } else if (status === 400) {
        error.value = data?.message || '请求参数错误';
      } else if (status === 500) {
        error.value = '服务器内部错误，请稍后重试';
      } else {
        error.value = `服务器错误 (${status}): ${data?.message || err.message}`;
      }
    } else if (err.request) {
      // 请求已发出但没有收到响应
      error.value = '无法连接到服务器，请检查网络连接';
      networkError.value = '网络连接失败，请确保后端服务正在运行';
    } else {
      // 其他错误
      error.value = err.message || '操作失败，请重试';
    }
  } finally {
    loading.value = false;
  }
};

const toggleMode = () => {
  isLogin.value = !isLogin.value;
  clearForm();
};

const clearForm = () => {
  formData.username = '';
  formData.password = '';
  formData.confirmPassword = '';
  error.value = '';
};

// 登录后自动设置设备
const setupDeviceAfterLogin = async () => {
  try {
    console.log('开始自动设置设备...');
    
    // 生成稳定的设备ID
    const deviceId = await generateStableDeviceId();
    console.log('生成的设备ID:', deviceId);
    
    // 验证设备ID
    if (!deviceId || deviceId === 'undefined' || deviceId === 'null') {
      throw new Error('设备ID生成失败');
    }
    
    // 尝试注册设备到后端（需要认证）
    try {
          const deviceResponse = await deviceAPI.register('手机设备', deviceId);
      console.log('设备注册成功:', deviceResponse);
    } catch (registerError) {
      console.warn('设备注册失败，尝试关联匿名设备:', registerError);
      
      // 如果注册失败，尝试关联匿名设备
      try {
        await deviceAPI.claimDevice(deviceId);
        console.log('匿名设备关联成功:', deviceId);
      } catch (claimError) {
        console.warn('设备关联也失败，但继续使用设备ID:', claimError);
      }
    }
    
    // 设置设备ID到store
    store.setCurrentDeviceId(deviceId);
    console.log('设备ID已设置到store:', deviceId);
    
    // 连接WebSocket
    console.log('准备连接WebSocket，token:', store.token?.substring(0, 20) + '...', 'deviceId:', deviceId);
    communicationService.connect(store.token!, deviceId);
    
    console.log('设备设置完成');
  } catch (error) {
    console.error('设备设置失败:', error);
    // 设备设置失败不影响登录，只记录错误
  }
};

// 生成稳定的设备ID
const generateStableDeviceId = async (): Promise<string> => {
  console.log('开始生成设备ID...');
  
  // 尝试从localStorage获取已保存的设备ID
  const storedDeviceId = localStorage.getItem('smartinput-mobile-device-id');
  if (storedDeviceId) {
    console.log('使用已保存的设备ID:', storedDeviceId);
    return storedDeviceId;
  }
  
  console.log('没有找到已保存的设备ID，开始生成新的...');
  
  // 生成新的设备ID
  const identifiers = [];
  
  // 获取设备信息
  const userAgent = navigator.userAgent;
  const screenInfo = `${screen.width}x${screen.height}`;
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  const language = navigator.language;
  const platform = navigator.platform;
  
  identifiers.push(userAgent);
  identifiers.push(screenInfo);
  identifiers.push(timezone);
  identifiers.push(language);
  identifiers.push(platform);
  
  if ('hardwareConcurrency' in navigator) {
    identifiers.push(navigator.hardwareConcurrency.toString());
  }
  
  if ('deviceMemory' in navigator) {
    identifiers.push(navigator.deviceMemory.toString());
  }
  
  console.log('设备信息收集完成:', {
    userAgent: userAgent.substring(0, 50) + '...',
    screenInfo,
    timezone,
    language,
    platform,
    identifiersCount: identifiers.length
  });
  
  // 生成哈希
  const combinedInfo = identifiers.join('|');
  console.log('组合信息长度:', combinedInfo.length);
  
  const hash = await generateHash(combinedInfo);
  console.log('生成的哈希:', hash.substring(0, 20) + '...');
  
  const deviceId = `mobile_${hash.substring(0, 16)}`;
  console.log('最终设备ID:', deviceId);
  
  // 保存到localStorage
  localStorage.setItem('smartinput-mobile-device-id', deviceId);
  console.log('设备ID已保存到localStorage');
  
  return deviceId;
};





// 生成哈希
const generateHash = async (input: string): Promise<string> => {
  try {
    // 检查 crypto.subtle 是否可用
    if (!crypto || !crypto.subtle) {
      console.warn('crypto.subtle 不可用，使用备用方案');
      return generateSimpleHash(input);
    }
    
    const encoder = new TextEncoder();
    const data = encoder.encode(input);
    const hashBuffer = await crypto.subtle.digest('SHA-256', data);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
  } catch (error) {
    console.warn('SHA-256 哈希生成失败，使用备用方案:', error);
    return generateSimpleHash(input);
  }
};

// 备用哈希生成函数
const generateSimpleHash = (input: string): string => {
  let hash = 0;
  if (input.length === 0) return hash.toString();
  
  for (let i = 0; i < input.length; i++) {
    const char = input.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // 转换为32位整数
  }
  
  // 转换为16位十六进制字符串
  return Math.abs(hash).toString(16).padStart(8, '0');
};
</script>

<style scoped>
.btn-primary {
  @apply bg-blue-600 text-white font-medium py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors;
}

.card {
  @apply bg-white rounded-lg shadow-lg p-6;
}
</style> 